package com.bawei.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsDocService;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.domain.vo.EsDocQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final String INDEX_NAME="product_sku_info";


    @Override
    public R<Boolean> batchInsertDocs(List<EsDocInsertVo> esDocInsertVo) {
        BulkRequest request = new BulkRequest();
        for (EsDocInsertVo docInsertVo : esDocInsertVo) {
            request.add(new IndexRequest(docInsertVo.getIndexName())
                    .id(docInsertVo.getId())
                    .source(JSONObject.toJSONString(docInsertVo.getData()), XContentType.JSON));
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            return R.ok(true, "插入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "插入失败");
    }


    /**
     * 高亮
     * @param searchReq
     * @return
     */
    @Override
    public R<List<Map>> queryDocs(EsDocQueryVo searchReq) {
        if (StringUtils.isEmpty(searchReq.getKeyWord())){
            throw new ServiceException("搜索参数不可以为空");
        }
        // 若未查询到数量结果，直接进行返回
        List<Map> productInfoResponseList = new ArrayList<>();

        SearchRequest searchRequest = new SearchRequest(searchReq.getIndexName());
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<String> fields = searchReq.getSearchFields();
        String[] array = fields.toArray(new String[fields.size()]);
        // 热词搜索参数
        if(array!=null){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(
                    searchReq.getKeyWord(), array);
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }
        // 分页
        searchSourceBuilder.from((searchReq.getPageVo().getCurrentPage() - 1) * searchReq.getPageVo().getPageSize());
        searchSourceBuilder.size(searchReq.getPageVo().getPageSize());

        searchSourceBuilder.query(boolQueryBuilder);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        List<String> highlightFields1 = searchReq.getHighlightFields();
        if(CollectionUtils.isEmpty(highlightFields1)){
            highlightFields1=searchReq.getSearchFields();
        }
        for (String s : highlightFields1) {
            highlightBuilder.field(s);
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchResponseHits = searchResponse.getHits();
            TotalHits totalHits = searchResponseHits.getTotalHits();
            SearchHit[] searchHits = searchResponseHits.getHits();
            for (SearchHit searchHit : searchHits) {
                // 源数据
                String sourceAsString = searchHit.getSourceAsString();
                Map<String,Object> productInfoResponse = JSONObject.parseObject(sourceAsString, Map.class);
                // 高亮
                Map<String, HighlightField> highlightFields =
                        searchHit.getHighlightFields();
                for (String field : highlightFields1) {
                    if (highlightFields != null){
                        HighlightField highlightField = highlightFields.get(field);
                        if (highlightField != null){
                            // 拼装
                            Text[] fragments = highlightField.getFragments();
                            StringBuilder sb = new StringBuilder();
                            for (Text fragment : fragments) {
                                sb.append(fragment);
                            }
                            productInfoResponse.put(field,sb.toString());
                        }
                    }
                }
                productInfoResponseList.add(productInfoResponse);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok(productInfoResponseList);
    }


    /**
     * 根据ids删除索引中的数据
     * @param docIds
     * @param indexName
     * @return
     */
    @Override
    public R<Boolean> deleteDocsById(Integer[] docIds, String indexName) {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueMinutes(2)); // 设置超时时间

        for (Integer docId : docIds) {
            DeleteRequest deleteRequest = new DeleteRequest(indexName, String.valueOf(docId));
            bulkRequest.add(deleteRequest);
        }
        try {
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常情况
            return R.fail("批量删除操作失败：" + e.getMessage());
        }
        return  null;
    }

    /**
     * 自动补全热词
     * @param indexName
     * @param keyWord
     * @param suggestionFiled
     * @return
     */
    @Override
    public List<String> querySuggestions(String indexName, String keyWord, String suggestionFiled) {
        SearchRequest request = new SearchRequest(indexName);
        ArrayList<String> list = new ArrayList<>();
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion(suggestionFiled)
                        .prefix(keyWord)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Suggest suggest = response.getSuggest();
        suggest.getSuggestion("suggestions").forEach(suggestion -> {
            suggestion.getOptions().forEach(entry -> {
                list.add(entry.getText().toString());
            });
        });
        return list;
    }
}
